<template>
  <pageTabelLayout :loadings="pageData.loading">
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form
            ref="searchFormRef"
            size="small"
            :model="pageData"
            :rules="searchRules"
            layout="inline"
          >
            <a-row>
              <!-- <a-col :span="4.8">
                <CorporateSectorCascader
                  :configCascader="configCascader"
                  @changeCascader="changeCascader"
              /></a-col> -->
              <a-col :span="4.8">
                <a-form-item label="退坯单号" prop="tpdh">
                  <a-input
                    allow-clear
                    :style="{ width: '200px' }"
                    class="bacClass"
                    v-model="pageData.tpdh"
                  /> </a-form-item
              ></a-col>
              <!-- <a-col :span="4.8">
                <a-form-item label="状态" prop="state">
                  <a-select
                    allow-clear
                    :style="{ width: '200px' }"
                    class="bacClass"
                    v-model="pageData.state"
                  >
                    <a-option value="0" label="未入库">未入库</a-option>
                    <a-option value="1" label="已入库">已入库</a-option>
                    <a-option value="2" label="全部">全部</a-option>
                  </a-select>
                </a-form-item>
              </a-col> -->
              <a-col :span="4.8">
                <a-form-item label="创建日期" field="beginDate">
                  <a-date-picker
                    popup-container="html"
                    v-model="pageData.beginDate"
                    :style="{ width: '230px' }"
                    placeholder="选择开始日期"
                    class="bacClass"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="4.8">
                <a-form-item label="至" field="endDate">
                  <a-date-picker
                    popup-container="html"
                    v-model="pageData.endDate"
                    :style="{ width: '240px', marginLeft: '25px' }"
                    placeholder="选择开始日期"
                    class="bacClass"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="4.8">
                <CorporateSectorCascader
                  :configCascader="configCascader2"
                  @changeCascader="changeCascader2"
              />
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div>
          <Toolbar :items="toolbarList" @select="handleSelect"> </Toolbar>
        </div>
      </div>

      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="gang"></div>
    </template>
    <template #pageTabel>
      <div class="w-full h-full">
        <encapsulation-agrid ref="table1Ref" :configaggrid="configaggrid"></encapsulation-agrid>
      </div>
    </template>
    <!-- 退坯入库 弹窗 -->
    <a-modal
      v-model:visible="returnGrayInStockModal"
      :on-before-ok="returnGrayInStockModalOk"
      :ok-loading="modalData.okLoading"
      @cancel="handleModalCancel"
      title="退坯入库"
      fullscreen
      :unmount-on-close="true"
      modal-class="inStockModal"
    >
      <a-form ref="formRef" size="small" :model="modalData" :rules="formRules" layout="inline">
        <a-row>
          <a-col :span="4.8">
            <a-form-item label="公司" field="firm" label-col-flex="80px">
              <CompanyCascader
                ref="cascaderRef"
                :configCascader="configCascader"
                @changeCascader="changeCascader"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="入库仓库" field="inStockWarehouse" label-col-flex="80px">
              <a-select
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                :field-names="warehouseFieldNames"
                :options="pageData.inShelveList"
                v-model="modalData.inStockWarehouse"
                @focus="focusShelve"
                @change="handleWarehouseChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="入库单号" prop="inStockOrder" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="modalData.inStockOrder"
                disabled
              />
            </a-form-item>
          </a-col>

          <a-col :span="4.8">
            <a-form-item label="入库类型" prop="inStockType" label-col-flex="80px">
              <a-select
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="modalData.inStockType"
                disabled
              >
                <a-option value="27"> 染厂退坯入库 </a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="4.8">
            <a-form-item label="日期" prop="date" label-col-flex="80px">
              <a-date-picker
                v-model="modalData.date"
                style="width: 200px"
                class="bacClass"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="送货单位" prop="deliveryCompanyName" label-col-flex="80px">
              <a-input v-model="modalData.deliveryCompanyName" style="width: 200px"
              class="bacClass" disabled></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4.8">
            <a-form-item label="贸易商" field="mys" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '210px' }"
                class="bacClass"
                v-model="modalData.mys"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="库存组织" prop="kczz" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '210px' }"
                class="bacClass"
                v-model="modalData.kczz"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="结算单位" prop="jsdw" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="modalData.jsdw"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="发货仓库" prop="fhck" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="modalData.fhck"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="4.8">
            <a-form-item label="备注" prop="remark" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="modalData.remark"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div style="width: 100%; height: calc(100vh - 220px); margin-top: 20px">
        <encapsulation-agrid ref="table4Ref" :configaggrid="configaggrid4"></encapsulation-agrid>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>
<script setup lang="ts">
  import { tableColumns, tableColumns5 } from './tableConfig'
  import { ref, reactive, onMounted } from 'vue'
  import { post } from '@/api/http'
  import Toolbar from '@/components/Toolbar.vue'
  import CompanyCascader from '@/components/CompanyCascader/index.vue'
  import usePermission from '@/store/modules/permission'
  import { ElMessage } from 'element-plus'
  import emitter from '@/hooks/useEventBus'
  import dayjs from 'dayjs'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'

  const today = dayjs()
  const pageData = reactive({
    loading: false,
    companyId: '',
    inShelveList: [],
    deliveryCode: '',
    state: '',
    date: '',
    beginDate: '',
    endDate: '',
    deliveryCompanyName:''
  })
  const modalData = reactive({
    okLoading: false,
    deliveryCode: '',
    firm: '',
    firmName: '',
    inStockWarehouse: '',
    inStockWarehouseName: '',
    inStockOrder: '',
    inStockType: '27',
    inStockTypeName: '染厂退坯入库',
    date: today.format('YYYY-MM-DD'),
    mys: '',
    kczz: '档口',
    jsdw: '巨丰盛',
    fhck: '粤隆染厂坯布仓',
    remark: '',
    deliveryCompanyName:''
  })
  //因为公司下拉是一个组件 这里监听公司清空
  watch(
    () => modalData.firm,
    (newVal) => {
      if (!newVal) {
        //如果公司清空 表格的布笼下拉也清空
        handleWarehouseChange(null)
      }
    }
  )
  const warehouseFieldNames = { value: 'id', label: 'warehouseName' }
  const handleWarehouseChange = (e: any) => {
    const obj: any = pageData.inShelveList.find((item: any) => item.id == e)
    if (obj) modalData.inStockWarehouseName = obj.warehouseName
    localStorage.setItem('pending-warehouseId', JSON.stringify(e))
    emitter.emit('pending-warehouseId', e)
  }
  const searchRules = reactive({
    beginDate: [
      {
        required: true,
        message: '请选择开始日期',
        trigger: 'change',
      },
    ],
    endDate: [
      {
        required: true,
        message: '请选择结束日期',
        trigger: 'change',
      },
    ],
  })
  const formRef = ref<any>(null)
  const formRules = reactive({
    firm: [
      {
        required: true,
        message: '公司必填',
        trigger: 'change',
      },
    ],
    inStockWarehouse: [
      {
        required: true,
        message: '入库仓库',
        trigger: 'change',
      },
    ],
  })
  const returnGrayInStockModal = ref<boolean>(false)
  const getModalTable = async (data: any) => {
    try {
      const res = await post({
        url: 'wms/GreyStockNewInDetail/getRCGreyReturnDetail',
        data,
      })
      if (res.code == 200) {
        nextTick(() => {
          const rowData = res.data.map((item: any) => {
            return {
              ...item,
              customerName: modalData.mys,
            }
          })
          returnGrayInStockModal.value = true
          nextTick(() => {
            table4Ref?.value.setdataListIterface(rowData)
            emitter.emit('pending-table4Ref', table4Ref)
          })
        })
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const saveParams = reactive<any>({
    stockInCode: '', //入库单号
    stockInDate: '', //入库时间
    stockInTypeId: '', //入库类型id
    stockInTypeName: '', //入库类型
    companyId: '', //公司id
    companyName: '', //公司
    warehouseId: '', //仓库id
    warehouseName: '', //仓库
    customName: '', //客户
    deliveryCompanyName:'',//送货单位
    deliveryCode: '', //收料单号
    remark: '', //备注
    GreyStockNewInDetail: [], //表格数据
  })
  const returnGrayInStockModalOk = async () => {
    try {
      const valid = await formRef.value.validate()
      if (valid) return false
      if (table4Ref.value.getListData().some((item: any) => !item.shelveCode)) {
        ElMessage.error('请填写布隆！')
        return false
      }
      modalData.okLoading = true
      saveParams.stockInCode = modalData.inStockOrder
      saveParams.stockInDate = modalData.date
      saveParams.stockInTypeId = modalData.inStockType
      saveParams.stockInTypeName = modalData.inStockTypeName
      saveParams.companyId = modalData.firm
      saveParams.companyName = modalData.firmName
      saveParams.warehouseId = modalData.inStockWarehouse
      saveParams.warehouseName = modalData.inStockWarehouseName
      saveParams.customName = modalData.mys
      saveParams.deliveryCompanyName = modalData.deliveryCompanyName
      saveParams.deliveryCode = modalData.deliveryCode
      saveParams.remark = modalData.remark
      saveParams.GreyStockNewInDetail = table4Ref.value.getListData()
      const res = await post({
        url: 'wms/GreyStockNewIn/insertList',
        data: saveParams,
      })
      if (res.code == 200) {
        ElMessage.success(res.message)
        return true
      } else {
        ElMessage.error(res.message)
        return false
      }
      console.log('saveParams', saveParams)
    } catch (e) {
      console.log(e)
      return false
    } finally {
      modalData.okLoading = false
    }
  }
  const inStockHandle = async (data: any) => {
    try {
      localStorage.removeItem('pending-warehouseId')
      const { deliveryCode, greyCode, customName ,deliveryCompanyName} = data
      const res = await post({
        url: 'wms/GreyStockNewIn/getCodeGenerate',
        data: {},
      })
      if (res.code == 200) {
        modalData.inStockOrder = res.data
      } else {
        ElMessage.error('入库单号获取失败！')
      }
      modalData.mys = customName
      modalData.deliveryCode = deliveryCode
      modalData.deliveryCompanyName = deliveryCompanyName
      getModalTable({ deliveryCode, greyCode })
    } catch (e) {
      console.log(e)
    }
  }
  const handleModalCancel = () => {
    modalData.inStockOrder = ''
    modalData.remark = ''
    modalData.firm = ''
    console.log('关闭弹窗', modalData.firm)
    modalData.firmName = ''
    modalData.inStockWarehouseName = ''
    modalData.inStockWarehouse = ''
    returnGrayInStockModal.value = false
    localStorage.removeItem('pending-warehouseId')
  }
  onMounted(() => {
    pageData.beginDate = today.subtract(6, 'day').format('YYYY-MM-DD')
    pageData.endDate = today.format('YYYY-MM-DD')
    emitter.on('ReturnGrayInStock-PendingInStockHandle', (data: any) => inStockHandle(data))
  })
  onUnmounted(() => {
    emitter.off('ReturnGrayInStock-PendingInStockHandle', (data: any) => inStockHandle(data))
  })
  const activeNames = ref<string[]>(['1', '2'])
  const permissionStore = usePermission()
  const toolbarList: any = ref([`${!permissionStore.hasPermisson('tprk.yclcx') ? '查询' : ''}`])
  const headerShow = ref<boolean>(true)
  const searchFormRef = ref<any>(null)
  const handleSelect = async () => {
    try {
      const valid = await searchFormRef.value?.validate()
      if (valid) return
      pageData.loading = true
      table1Ref.value.setQuery({
        deliveryCode: pageData.deliveryCode,
        deliveryCompanyName:pageData.deliveryCompanyName.replace(/\s/g, ''),
        beginDate: pageData.beginDate,
        endDate: pageData.endDate,
      })
    } catch (e) {
      console.log(e)
    } finally {
      pageData.loading = false
    }
  }
  const configCascader = ref<{}>({
    corporateWidth: '210px', //公司宽度
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '', //公司label
    cascaderShow: 'sector', //配置部门不显示
  })
  const table1Ref = ref<any>(null)
  let configaggrid = ref({
    url: 'wms/GreyStockNewIn/getRCGreyReturnDataLink', //接口路径
    queryData: {
      deliveryCode: pageData.deliveryCode,
      deliveryCompanyName:pageData.deliveryCompanyName.replace(/\s/g, ''),
      beginDate: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
      endDate: dayjs().format('YYYY-MM-DD'),
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
    fileName: 'ReturnGrayInStock-Pending-1',
  })
  const table4Ref = ref<any>(null)
  let configaggrid4 = ref({
    url: '', //接口路径
    queryData: {},
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns5,
    fileName: 'ReturnGrayInStock-Pending-4',
  })
  const focusShelve = async () => {
    try {
      let { code, data, message } = await post({
        url: 'wms/warehouse/getWarehouseByPara',
        data: { firmId: modalData.firm, warehouseTypeName: '坯布仓,次布仓', virtuallyState: 0 },
      })
      if (code == 200) {
        pageData.inShelveList = data
        if (data.length == 1) {
          modalData.inStockWarehouse = data[0].id
          modalData.inStockWarehouseName = data[0].warehouseName
          handleWarehouseChange(data[0].id)
        }
        return
      }
      ElMessage.error(message)
    } catch (e) {
      console.log(e)
    }
  }
  const changeCascader = (data: any) => {
    formRef.value.resetFields()
    console.log('datadata', data)
    const { corporateId, corporateLabel } = data
    modalData.firm = corporateId
    modalData.firmName = corporateLabel
    modalData.inStockWarehouse = ''
    modalData.inStockWarehouseName = ''
    focusShelve()
  }

  const configCascader2 = ref<{}>({
    corporateWidth: '230px', //公司宽度
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '送货单位', //公司label
    cascaderShow: 'sector', //配置部门不显示
  })
  const changeCascader2 = (data: any) => {
    const { corporateId, corporateLabel } = data
    pageData.deliveryCompanyName = corporateLabel
  }
</script>

<style scoped>
  :deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  :deep(.arco-picker input) {
    padding-left: 0 !important;
  }
  :deep(.arco-picker) {
    padding-left: 0 !important;
  }
  :deep(.arco-picker-separator) {
    padding: 0 !important;
  }
</style>
<style>
  .el-scrollbar__view {
    height: 100%;
  }
</style>
